#include "command.h"
#include "parser.h"
#include <stdlib.h>
#include <stdio.h>

listCommand createListCommand(void) {
	listCommand l;
	
	l = (listCommand)malloc(sizeof(struct _LINKED_LIST_COMMAND));

	if(l == NULL) {
		return NULL;
	} else {
		l->size = 0;
		l->head = NULL;

		return l;
	}
}

int prependNodeCommand(listCommand l, char **commands, int size) {

	nodeCommand n;
        nodeCommand new_node;

        n = l->head;

        new_node = (nodeCommand)malloc(sizeof(struct _NODE_COMMAND));
        new_node->command_list = commands;
	new_node->size = size;
        new_node->next = NULL;
        
        if(new_node == NULL) {
                return 0;
        }

        if(n == NULL) {
                l->head = new_node;     
                (l->size)++;
                return 1;
        } else {
                while(n->next != NULL) {
                        n = n->next;
                }

                n->next = new_node;
                (l->size)++;
                return 1;
        }
}

int execute(char **commands, int n, nodeCommand node) {
        int pid;
        int wait_status;
        int i;
	FILE *f;

        pid = fork();

        if(pid < 0) {
                printf("Erro!\n");
                return -1;
        } else if(pid == 0) {
                //child
		if(node->next != NULL)
		{
				fprintf(stderr,"entrou\n");
				f = freopen("temp.txt","w",stdout);
		}
                char **arg;

                arg = (char **)malloc((n+1)*sizeof(char *));
                for(i=0;i<n;i++) {
                        arg[i] = commands[i];
                }
                arg[i] = NULL;

		if(strcmp(arg[i-1],"") == 0)
			arg[i-1] = NULL;
                if(execvp(commands[0],arg)==-1) {
                        return -1;
                }
        } else {
                //father
                wait(&wait_status);
		//fclose(f);
                return 1;
        }

        return 1;
}


int main(void) {
	char **pipes;	
	char command[] = {"ls -l | grep command | less"};
	int i,n,lixo,j,exec_count=0;
	char *temp_file = "temp.txt";

	listCommand l = createListCommand();
	nodeCommand node;

	pipes = parser(command,&n,'|');

	for(i=0;i<n;i++) {
		char **commands;
		pipes[i] = normalizeString(pipes[i]);
		commands = parser(pipes[i],&lixo,' ');
		prependNodeCommand(l,commands,lixo);
	}

	node = l->head;

	while(node != NULL) {
		FILE *f;
		if(exec_count != 0)
			f = freopen(temp_file,"r",stdin);
		//for(i=0;i<node->size;i++) {
		//	printf("%s|",node->command_list[i]);
		//}
		//printf("\n");
		execute(node->command_list,node->size,node);
		//fclose(f);
		node = node->next;
		exec_count++;
	}
/*
	freopen("temp.txt","w",stdout);
	printf("teste");
*/
	return 0;
}
